#include "logininterface.h"
#include "ui_logininterface.h"
#include "mainwindow.h"
#include <QHttpPart>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QRegExpValidator>
#include "operationdocument.h"
#include <QDir>
#include <QTimer>
#include "function/function.h"

QByteArray token;//http返回id码

LoginInterface::LoginInterface(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginInterface)
{
    ui->setupUi(this);

    //设置窗口标题
    setWindowTitle("信瑞琅玥");

    initialize();//初始化界面

    //初始化定时器对象
    mytimer=new QTimer(this);
    //设置定时时间
    mytimer->setInterval(60000);  //1分钟
    //关联timeout()信号与自定义的槽函数
    connect(mytimer,SIGNAL(timeout()),this,SLOT(timer()));
    //启动定时器
    mytimer->start();

}

LoginInterface::~LoginInterface()
{
    delete ui;
}

//清除密码输入框
void LoginInterface::clearPassword()
{
    ui->lineEdit_2->setText("");
}

void LoginInterface::timer()
{
    //创建QDir的对象
    QDir mydir(QString("%1logfile/").arg(MY_PATH));
    //遍历目录，打印目录中的内容
    QStringList filelist=mydir.entryList();

    for(int i=0; i<filelist.size(); i++)
    {
        if(filelist.at(i)=="."||filelist.at(i)=="..")
        {
            continue;
        }

        //拼接得到文件的绝对路径
        QString Path=QString("%1logfile/%2").arg(MY_PATH).arg(filelist.at(i));

        QFileInfo info(Path);

//        QString infoList;
//        infoList += QString("size: %1\n").arg(info.size());
//        infoList += QString("createdTime: %1\n").arg(info.birthTime().toString("yyyy-MM-dd hh:mm:ss"));
//        infoList += QString("modifiedTime: %1\n").arg(info.lastModified().toString("yyyy-MM-dd hh:mm:ss"));
//        infoList += QString("lastReadTime: %1\n").arg(info.lastRead().toString("yyyy-MM-dd hh:mm:ss"));
//        std::cout << infoList.toStdString() << std::endl;


        QDateTime time1 = info.birthTime();
        QDateTime time2 = QDateTime::currentDateTime();
        int days = time1.daysTo(time2);//计算两个日期天数差
//        int secs = time1.secsTo(time2);//计算两个日期秒数差
//        std::cout << days << std::endl;
//        std::cout << secs << std::endl;

        if(days > 7)
        {
            //文件保留7天后自动删除
            OperationDocument::DeleteFileOrFolder(Path);
        }
    }
}

//点击了登入按钮
void LoginInterface::on_pushButton_clicked()
{
    QString username = ui->lineEdit->text();//获取登入账号
    QString password = ui->lineEdit_2->text();//获取登入密码


    QNetworkRequest request;

    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    request.setUrl(QUrl::fromUserInput(URLName_2("login/")));

    QJsonObject object;
    object.insert("username",username);
    object.insert("password",password);

    QByteArray byte_array = QJsonDocument(object).toJson();
    qDebug()<< "user  info " << object;
//    QNetworkReply* reply = naManager->post(request,byte_array);//发起post请求
    naManager.post(request,byte_array);//发起post请求

}

//隐藏，显示密码
void LoginInterface::on_pushButton_2_clicked()
{
//    //设置密码隐藏
//    if(Password_conceal)
//    {
//        Password_conceal=false;
//        ui->lineEdit_2->setEchoMode(QLineEdit::Password);//隐藏密码
//        ui->pushButton_2->setStyleSheet("border-image: url(:/new/prefix1/resource/4.png);");
//    }
//    else
//    {
//        Password_conceal=true;
//        ui->lineEdit_2->setEchoMode(QLineEdit::Normal);//显示密码
//        ui->pushButton_2->setStyleSheet("border-image: url(:/new/prefix1/resource/5.png);");
//    }

    ui->lineEdit_2->setText("");
}

//初始化界面
void LoginInterface::initialize()
{
    //只能输入字母和数字
    ui->lineEdit->setValidator(new QRegExpValidator(QRegExp("[a-zA-Z0-9]+$")));

    //部件事件过滤的注册
    ui->pushButton->installEventFilter(this);
    ui->pushButton_2->installEventFilter(this);
    ui->pushButton_3->installEventFilter(this);

    //关联http信号与槽
    connect(&naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));

    QFont font;
    font.setLetterSpacing(QFont::PercentageSpacing,120);//120字间距，默认100
    ui->label_3->setFont(font);
    ui->label_4->setFont(font);
    ui->lineEdit->setFont(font);
    ui->lineEdit_2->setFont(font);

    //隐藏密码错误提示
    ui->label_3->hide();
    //当输入框没有内容时禁止登入按钮
    ui->pushButton->setEnabled(false);
    //自定义一键清除输入框内容->先隐藏
    ui->pushButton_3->hide();
    ui->pushButton_2->hide();

//    //开启一键清除输入框内容
//    ui->lineEdit->setClearButtonEnabled(true);
//    ui->lineEdit_2->setClearButtonEnabled(true);

    ui->lineEdit_2->setEchoMode(QLineEdit::Password);//隐藏密码
}

bool LoginInterface::eventFilter(QObject *watched, QEvent *event)
{
    if(ui->pushButton==watched)
    {
        if(QEvent::Enter==event->type())
        {
            if(ifclick)
            {
                setCursor(Qt::PointingHandCursor); //设置鼠标样式
            }
        }
        else if(QEvent::Leave==event->type())
        {
            setCursor(Qt::ArrowCursor); //设置鼠标样式
        }
    }
    if(ui->pushButton_2==watched)
    {
        if(QEvent::Enter==event->type())
        {
            setCursor(Qt::PointingHandCursor); //设置鼠标样式
        }
        else if(QEvent::Leave==event->type())
        {
            setCursor(Qt::ArrowCursor); //设置鼠标样式
        }
    }
    if(ui->pushButton_3==watched)
    {
        if(QEvent::Enter==event->type())
        {
            setCursor(Qt::PointingHandCursor); //设置鼠标样式
        }
        else if(QEvent::Leave==event->type())
        {
            setCursor(Qt::ArrowCursor); //设置鼠标样式
        }
    }

    return QObject::eventFilter(watched,event);
}

//接收网络响应槽函数
void LoginInterface::requestFinished(QNetworkReply *reply)
{
    QString loginResultJson;
    bytes = reply->readAll();
//    qDebug()<<__LINE__<<bytes;

    // 获取http状态码
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(statusCode.isValid())
    {
//        qDebug() << "status code=" << statusCode.toInt();
    }

    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError)
    {
        qDebug() << "Failed: " << reply->errorString();
    }
    else
    {
        // 获取返回内容
        //qDebug() << "loginResultJson  is  " <<  QString::fromStdString(bytes.toStdString());
        loginResultJson =  QString::fromStdString(bytes.toStdString());
        //处理返回数据
    }

    //把获取的json数据标准化存储
    QJsonParseError myerr;
    QJsonDocument mydoc=QJsonDocument::fromJson(bytes,&myerr);

    //获取最外面的对象
    QJsonObject obj=mydoc.object();

    QString name=obj.value("name").toString();
    qDebug()<<__LINE__<<"retInfo="<<name;
    if(!name.isEmpty())
    {
//        if(!ifWin)
        {
            ifWin = true;

            bytes = obj.value("token").toString().toUtf8();
            token = bytes;

            //登入成功，进入主界面
            w=new MainWindow();
            w->show();
            w->setbytes(bytes,name,this);

            this->hide();

        }


    }
    else
    {
        ui->label_3->show();
    }

}

//账号输入框按下回车时触发
void LoginInterface::on_lineEdit_returnPressed()
{
    //光标移到密码输入框
    ui->lineEdit_2->setFocus();
}

//密码输入框按下回车时触发
void LoginInterface::on_lineEdit_2_returnPressed()
{
    if(!ui->lineEdit->text().isEmpty() && !ui->lineEdit_2->text().isEmpty())
    {
        on_pushButton_clicked();
    }

}

//当账号输入框QLineEdit中的文本改变时，发出此信号，text是新的文本。当通过程序改变文本时，也会触发此信号
void LoginInterface::on_lineEdit_textChanged(const QString &arg1)
{
    //隐藏密码错误提示
    ui->label_3->hide();

    if(arg1.isEmpty())
    {
        ui->pushButton_3->hide();
    }
    else
    {
        ui->pushButton_3->show();
    }

    if(arg1.isEmpty() || ui->lineEdit_2->text().isEmpty())
    {
        //当输入框没有内容时禁止登入按钮
        ifclick = false;

        ui->pushButton->setEnabled(false);
        ui->pushButton->setStyleSheet("background: #cccccc;font-size: 18px;font-family: Microsoft YaHei;color: #FBFBFB;border-radius: 25px;");
    }
    else
    {
        ifclick = true;

        ui->pushButton->setEnabled(true);
        ui->pushButton->setStyleSheet("background: #1B89CB;font-size: 18px;font-family: Microsoft YaHei;color: #FBFBFB;border-radius: 25px;");
    }
}

//当密码输入框QLineEdit中的文本改变时，发出此信号，text是新的文本。当通过程序改变文本时，也会触发此信号
void LoginInterface::on_lineEdit_2_textChanged(const QString &arg1)
{
    //隐藏密码错误提示
    ui->label_3->hide();

    if(arg1.isEmpty())
    {
        ui->pushButton_2->hide();
    }
    else
    {
        ui->pushButton_2->show();
    }

    if(arg1.isEmpty() || ui->lineEdit->text().isEmpty())
    {
        //当输入框没有内容时禁止登入按钮
        ifclick = false;

        ui->pushButton->setEnabled(false);
        ui->pushButton->setStyleSheet("background: #cccccc;font-size: 18px;font-family: Microsoft YaHei;color: #FBFBFB;border-radius: 25px;");
    }
    else
    {
        ifclick = true;
        ui->pushButton->setEnabled(true);
        ui->pushButton->setStyleSheet("background: #1B89CB;font-size: 18px;font-family: Microsoft YaHei;color: #FBFBFB;border-radius: 25px;");
    }
}

void LoginInterface::on_pushButton_3_clicked()
{
    ui->lineEdit->setText("");
}
